package backtracking;

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;

/**
 * @Author: 海琳琦
 * @Date: 2022/2/26 17:13
 * https://leetcode-cn.com/problems/permutations-ii/
 */
public class PermuteUnique {

    static List<List<Integer>> result;
    static LinkedList<Integer> list;
    static int[] flagDeep;

    public List<List<Integer>> permuteUnique(int[] nums) {
        result = new ArrayList<>();
        list = new LinkedList<>();
        //Arrays.sort(nums);  对应backTracking1
        flagDeep = new int[nums.length];
        backTracking(nums);
        return result;
    }

    private void backTracking(int[] nums) {
        if (list.size() == nums.length) {
            result.add(new ArrayList<>(list));
            return;
        }
        //层次的去重数组大小和深度的去重数组大小不一样
        int[] flagLevel = new int[21];
        for (int i = 0; i < nums.length; i++) {
            if (flagLevel[nums[i] + 10] == 1 || flagDeep[i] == 1) {
                continue;
            }
            list.add(nums[i]);
            flagLevel[nums[i] + 10] = 1;
            flagDeep[i] = 1;
            backTracking(nums);
            list.removeLast();
            flagDeep[i] = 0;
        }
    }

    /**
     * 方法二
     * @param nums
     */
    private void backTracking1(int[] nums) {
        if (list.size() == nums.length) {
            result.add(new ArrayList<>(list));
            return;
        }
        //层次的去重数组大小和深度的去重数组大小不一样
        int[] flagLevel = new int[21];
        for (int i = 0; i < nums.length; i++) {
            if (flagDeep[i] == 1) {
                continue;
            }
            list.add(nums[i]);
            flagDeep[i] = 1;
            backTracking(nums);
            list.removeLast();
            flagDeep[i] = 0;
            while (i != nums.length && nums[i] == nums[i + 1]) {
                i++;
            }
        }
    }

    public static void main(String[] args) {

    }
}
